
from ...service.buss_mis.financial_account import FinancialAccountService
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.common import get_user_id_or_false, get_current_user_id, get_current_role_id, insert_data, find_data, update_data, delete_data, get_condition, get_info, get_current_organization_id
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
import hashlib
import re
import datetime
import uuid
import pandas as pd
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
from ...service.mongo_bill_service import MongoBillFilter
from ...service.buss_mis.comment_manage import CommentManageService
from enum import Enum
from ..constant import AccountType, AccountStatus, PayStatue, PayType
'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-07-29 18:09:15
@LastEditTime: 2020-03-04 16:49:29
@LastEditors: Please set LastEditors
'''
# -*- coding: utf-8 -*-

'''
服务选项函数
'''


class Financial():
    '''发送财务模块对象'''

    def __init__(self, user_id, org_id, amount, item):
        '''构造函数'''
        # # 用户ID
        # self.user_id = user_id
        # # 银行户主名
        # self.name = name
        # # 账户
        # self.card_id = account
        # # 金额
        # self.amount = amount
        # # 项目名称
        # self.item = item
        # # 组织id
        # self.organization_id = organization_id
        # # 截止日期
        # self.end_date = end_date
        # 付款方id
        self.pay_id = user_id
        # 收款方id
        self.receive_id = org_id
        # 金额
        self.amount = amount
        # 摘要
        self.abstract = item

    def to_dict(self):
        return self.__dict__


class CostStatus:
    '''服务记录发送状态'''
    success = '已发送'
    fail = '发送失败'


class ServiceRecordService(MongoService):
    ''' 服务记录 '''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.role_service = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.financial_account_service = FinancialAccountService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.comment_service = CommentManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_service_record_list_all(self, order_ids, condition, page, count):
        '''获取服务记录列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''

        if 'start_date' in list(condition.keys()):
            condition['start_date_s'] = condition['start_date'][0]
            condition['end_date_s'] = condition['start_date'][1]
        if 'end_date' in list(condition.keys()):
            condition['start_date_e'] = condition['end_date'][0]
            condition['end_date_e'] = condition['end_date'][1]
        service_worker_id = get_current_user_id(self.session)
        keys = ['user_filter', 'id', 'service_order_code', 'start_date_s', 'end_date_s',
                'start_date_e', 'end_date_e', 'service_project_id', 'service_worker_id', 'service_project_name', 'states']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('organization_id').inner(order_ids) & (C('servicer_id') == service_worker_id))\
            .lookup_bill('PT_User', 'servicer_id', 'id', 'user') \
            .lookup_bill('PT_Service_Product', 'service_product_id', 'id', 'product')\
            .lookup_bill('PT_Service_Order', 'order_id', 'id', 'order')\
            .lookup_bill('PT_Task', 'id', 'task_object_id', 'task')\
            .lookup_bill('PT_User', 'order.purchaser_id', 'id', 'purchaser_info')\
            .lookup_bill('PT_User', 'order.service_provider_id', 'id', 'service_provider_info')\
            .add_fields({'service_order_code': '$order.order_code',
                         'service_project_name': '$product.name',
                         'service_product_img': '$product.picture_collection',
                         'service_worker_id': '$user.name',
                         'service_provider_id': '$order.service_provider_id',
                         'purchaser_id': '$order.purchaser_id',
                         'task_begin_photo': self.ao.array_elemat('$task.begin_photo', 0),
                         'task_end_photo': self.ao.array_elemat('$task.end_photo', 0),
                         'task_state':  self.ao.array_elemat('$task.task_state', 0),
                         'task_name': '$task.task_name',
                         'task_address': '$task.task_address',
                         'task_id':  self.ao.array_elemat('$task.id', 0),
                         'task_remark': '$task.remark',
                         'purchaser_name': '$purchaser_info.name',
                         'service_provider_name': '$service_provider_info.name',
                         'purchaser_telephone': '$purchaser_info.personnel_info.telephone',
                         #  'start_date': self.ao.date_to_string('$start_date'),
                         #  'end_date': self.ao.date_to_string('$end_date'),
                         #  'start_date': self.ao.date_to_string('$start_date', '%Y-%m-%d %H:%M:%S'),
                         #  'end_date': self.ao.date_to_string('$end_date', '%Y-%m-%d %H:%M:%S')
                         })\
            .match_bill(C('service_order_code').like(values['service_order_code'])
                        & (C('id') == values['id'])
                        & (C('start_date') >= as_date(values['start_date_s']))
                        & (C('start_date') <= as_date(values['end_date_s']))
                        & (C('end_date') >= as_date(values['start_date_e']))
                        & (C('end_date') <= as_date(values['end_date_e']))
                        & (C('service_product_id') == values['service_project_id'])
                        & (C('task.task_state') == values['states'])
                        & (C('service_project_name').like(values['service_project_name']))
                        & (C('servicer_id') == values['service_worker_id']))

        # # 获取服务商超级管理员的角色ID
        # _filter_fwscg = MongoBillFilter()
        # _filter_fwscg.match_bill((C('role_type') == '服务商') & (
        #     C('name') == '服务商超级管理员')).project({'_id': 0})
        # res_fwscg = self.query(_filter_fwscg, 'PT_Role')

        # fwscg_role_id = res_fwscg[0]['id']

        # # 获取平台超级管理员的角色ID
        # _filter_ptcg = MongoBillFilter()
        # _filter_ptcg.match_bill((C('role_type') == '平台') & (
        #     C('name') == '超级管理员')).project({'_id': 0})
        # res_ptcg = self.query(_filter_ptcg, 'PT_Role')

        # ptcg_role_id = res_ptcg[0]['id']

        # 当前的角色ID
        # cur_role_id = get_current_role_id(self.session)
        _filter.project({'_id': 0, 'user._id': 0, 'order._id': 0,
                         'product._id': 0, 'task': 0, 'purchaser_info': 0, 'service_provider_info': 0})
        res = self.page_query(
            _filter, 'PT_Service_Record', page, count)
        # if res.get('result'):
        #     for result in res.get('result'):
        #         if result.get('purchaser_id'):
        #             _filter_pur = MongoBillFilter()
        #             _filter_pur.match_bill((C('id') == result.get(
        #                 'purchaser_id')[0])).project({'_id': 0})
        #             res_pur = self.query(_filter_pur, 'PT_User')
        #             result['purchaser_name'] = res_pur[0]['name'] if res_pur else ''
        #         if result.get('service_provider_id'):
        #             _filter_pro = MongoBillFilter()
        #             _filter_pro.match_bill((C('id') == result.get(
        #                 'service_provider_id')[0])).project({'_id': 0})
        #             res_pro = self.query(_filter_pro, 'PT_User')
        #             result['service_provider_name'] = res_pro[0]['name'] if res_pro else ''
        #         if result.get('task_begin_photo') and len(result.get('task_begin_photo')) > 0:
        #             result['task_begin_photo'] = result['task_begin_photo'][0]
        #         if result.get('task_end_photo') and len(result.get('task_end_photo')) > 0:
        #             result['task_end_photo'] = result['task_end_photo'][0]
        #         if result.get('task_state') and len(result.get('task_state')) > 0:
        #             result['task_state'] = result['task_state'][0]
        #         if result.get('task_id') and len(result.get('task_id')) > 0:
        #             result['task_id'] = result['task_id'][0]
        return res

    def update_service_record(self, service_record):
        '''# 新增/修改服务记录'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            if 'id' in service_record.keys():
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.serviceRecord.value, service_record, 'PT_Service_Record')
                if bill_id:
                    res = 'Success'
            else:
                bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                            TypeId.serviceRecord.value, service_record, 'PT_Service_Record')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_record_evaluate_list(self, condition, page=None, count=None):
        '''获取服务记录的评价列表
        '''
        data = {}
        if condition.get('record_id'):
            _filter = MongoBillFilter()
            _filter.match_bill(
                (C('id') == condition.get('record_id'))).project({"_id": 0})
            res = self.query(_filter, 'PT_Service_Record')
            if res:
                data['comment_object_id'] = res[0].get('item_id')
            else:
                return {'result': [], 'total': 0}
        res_com = self.comment_service.get_comment_list(N, data, page, count)
        # if not res_com['result']:
        #     return {'result':[],'total':0}
        return res_com

    def get_record_option_list(self, condition, page=None, count=None):
        '''获取服务记录的服务选项列表
        '''
        res = self.get_service_record_list_all(N, condition, 1, 1)
        option_list = []
        total = 0
        if res['result']:
            if res['result'][0].get('option_list'):
                option_list = res['result'][0].get('option_list')
                total = len(option_list)
        return {'result': option_list, 'total': total}

    def delete_service_record(self, service_record_ids):
        '''删除服务记录接口

        Arguments:
            servicr_option_ids   {ids}      数据id
        '''
        res = 'fail'

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(service_record_ids, str):
                ids.append(service_record_ids)
            else:
                ids = service_record_ids
            for service_record_ids in ids:
                # 查询被删除的数据信息
                data = find_data(db, 'PT_Service_Record', {
                    'id': service_record_ids, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.serviceRecord.value, data[0], 'PT_Service_Record')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def invoking_financial(self, record_ids):
        '''发送服务记录到财务模块'''
        res = 'Fail'
        _filter = MongoBillFilter()
        _filter.match_bill(C('id').inner(record_ids)) \
               .inner_join_bill('PT_Service_Order', 'order_id', 'id', 'order') \
               .inner_join('IEC_Check_In', 'order_id', 'order_id', 'check')\
               .inner_join_bill('PT_Service_Product', 'service_product_id', 'id', 'product')\
            .lookup_bill('PT_Service_Item', 'product.service_item_id', 'id', 'item')\
            .add_fields({
                'purchaser_id': '$check.user_id',
                'item_name': '$item.name',
                'organization_id': '$item.organization',
                'create_date': self.ao.date_to_string('$create_date'),
                'modify_date': self.ao.date_to_string('$modify_date')})\
            .lookup_bill('PT_User', 'purchaser_id', 'id', 'user')\
            .add_fields({
                'account': '$user.personnel_info.card_number',
                'account_name': '$user.name'})\
            .project({'_id': 0, 'order._id': 0, 'item._id': 0, 'user._id': 0, 'item._id': 0, 'check._id': 0, 'product._id': 0})
        record_datas = self.query(_filter, "PT_Service_Record")
        financial_list = []
        success_ids = []
        fail_ids = []
        org_id = get_current_organization_id(self.session)
        if record_datas:
            for record in record_datas:
                purchaser_id = ''
                if len(record['purchaser_id']) > 0:
                    # print('用户id  ',record['purchaser_id'])
                    purchaser_id = record['purchaser_id']
                # account = ''
                # if len(record['account']) > 0:
                #     account = record['account'][0]
                # else:
                #     fail_ids.append(record['id'])
                #     continue
                # account_name = ''
                # if len(record['account_name']) > 0:
                #     account_name = record['account_name'][0]
                # else:
                #     fail_ids.append(record['id'])
                #     continue
                item_name = ''
                if len(record['item_name']) > 0:
                    item_name = record['item_name'][0]
                # organization_id = ''
                # if len(record['organization_id']) > 0:
                #     organization_id = record['organization_id'][0]
                financial = Financial(
                    purchaser_id, org_id, record['valuation_amount'], item_name)
                financial_list.append(financial.to_dict())
                success_ids.append(record['id'])
            print(financial_list, 'financial_list>>>>>>')
            print(success_ids, 'success_ids>>>>>')
            print(fail_ids, 'fail_ids>>>>')
            result = self.financial_account_service.add_bank_charge_data(
                financial_list)
            recode = []
            table_name = []
            if fail_ids:
                for recode_id in fail_ids:
                    recode.append(
                        {'id': recode_id, 'cost_status': CostStatus.fail})
                    table_name.append('PT_Service_Record')
            if success_ids:
                for recode_success_id in success_ids:
                    recode.append({'id': recode_success_id,
                                   'cost_status': CostStatus.success})
                    table_name.append('PT_Service_Record')
            bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                        TypeId.serviceRecord.value, recode, table_name)
            if result:
                res = 'Success'
        return res

    def get_servicer_report_month(self, condition):
        # 查询服务记录表
        arr = []
        _filter = MongoBillFilter()
        _filter.sort({'create_date': 1})\
            .project({'_id': 0})
        res_list = self.query(_filter, 'PT_Service_Record')
        print(res_list[1]['create_date'].year)
        print(res_list[len(res_list)-1]['create_date'].year)
        year = res_list[1]['create_date'].year
        while(year <= res_list[len(res_list)-1]['create_date'].year):
            # 根据年份分类
            month = 1
            while(month <= 12):
                if month < 12:
                    start = datetime.datetime(year, month, 1, 0, 0, 0)
                    end = datetime.datetime(
                        year, month + 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
                else:
                    start = datetime.datetime(year, month, 1, 0, 0, 0)
                    end = datetime.datetime(
                        year + 1, 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
                _filter = MongoBillFilter()
                _filter.match_bill((C('create_date') > start)
                                   & (C('create_date') < end))\
                    .lookup_bill('PT_Service_Order', 'order_id', 'id', 'order')\
                    .add_fields({'purchaser_id': '$order.purchaser_id'})\
                    .lookup_bill('PT_User', 'purchaser_id', 'id', 'user')\
                    .match_bill((C('user.organization_info.personnel_category') == '服务商'))\
                    .add_fields({'admin_area_id': '$user.admin_area_id'})\
                    .lookup_bill('PT_Administration_Division', 'admin_area_id', 'id', 'area')\
                    .add_fields({'parent_id': '$area.parent_id'})\
                    .lookup_bill('PT_Administration_Division', 'parent_id', 'id', 'parent_area')\
                    .add_fields({
                        'shequ': '$area.name',
                        'zhenjie': '$parent_area.name',
                        'valuation_amount': self.ao.switch([self.ao.case(((F('valuation_amount') == None)), 0.0)], '$valuation_amount'),
                    })\
                    .project({'_id': 0, 'order._id': 0, 'user._id': 0, 'area._id': 0, 'parent_area._id': 0})\
                    .group(
                        {
                            'purchaser_id': '$purchaser_id',
                            'shequ': '$shequ',
                            'zhenjie': '$zhenjie'
                        },
                        [{
                            'count': self.ao.summation('$valuation_amount')
                        }])\
                    .group(
                        {
                            'shequ': '$shequ',
                            'zhenjie': '$zhenjie'
                        },
                        [{
                            'count': self.ao.summation('$count')
                        },
                            {
                            'num': self.ao.summation(1)
                        }])\

                result = self.query(_filter, 'PT_Service_Record')
                print("哈哈哈哈哈哈哈哈哈哈哈哈", len(result))
                for item in result:
                    item['date'] = str(year) + '-' + str(month)
                arr.append({'res': result})
                month = month + 1
            year = year + 1
        return arr

    def get_order_report(self, org_list, condition, page, count):
        keys = ['org_id']
        values = self.get_value(condition, keys)
        res = {'result': []}
        _filter = MongoBillFilter()
        if 'month' in condition.keys() and len(condition['month']) == 7:
            # str类型,格式：yyyymm
            month = int(condition['month'][5:])
            year = int(condition['month'][0:4])
            start = datetime.datetime.now()
            end = datetime.datetime.now()
            if month < 12:
                start = datetime.datetime(year, month, 1, 0, 0, 0)
                end = datetime.datetime(
                    year, month + 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            else:
                start = datetime.datetime(year, month, 1, 0, 0, 0)
                end = datetime.datetime(
                    year + 1, 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            _filter.match_bill((C('create_date') > start)
                               & (C('create_date') < end))
        _filter.match((C('bill_status') == 'valid'))\
            .lookup_bill('PT_Service_Order', 'order_id', 'id', 'order')\
            .add_fields({'order_id': '$order.id'})\
            .add_fields({'service_provider_id': '$order.service_provider_id'})\
            .lookup_bill('PT_User', 'service_provider_id', 'id', 'user')\
            .match_bill((C('user.organization_info.personnel_category') == '服务商') & (C('service_provider_id') == values['org_id']))\
            .add_fields({'service_provider_name': '$user.name'})\
            .add_fields({'current_year': self.ao.to_string(self.ao.year('$create_date'))})\
            .add_fields({'current_month': self.ao.to_string(self.ao.month('$create_date'))})\
            .add_fields({'month': self.ao.concat([('$current_year'), '-', ('$current_month')])})\
            .project({'month': 1, 'valuation_amount': 1, 'order_id': 1, 'service_provider_name': 1})\
            .group(
            {
                'service_provider_name': '$service_provider_name',
                'order_id': '$order_id',
                'year_month': '$month',
            },
            [{
                'valuation_amount': self.ao.summation('$valuation_amount')
            }])\
            .group(
            {
                'service_provider_name': '$service_provider_name',
                'year_month': '$year_month',
            },
            [{
                'order_quantity': self.ao.summation(1)
            }, {
                'valuation_amount_total': self.ao.summation('$valuation_amount')
            }])\
            .sort({'year_month': 1})
        res_old_age = self.query(_filter, 'PT_Service_Record')
        res['result'] = res_old_age
        return res
